#include "gaussiandialog.h"
#include "ui_gaussiandialog.h"
#include <QPainter>

GaussianDialog::GaussianDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::GaussianDialog)
{
    ui->setupUi(this);

    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint & ~Qt::WindowMinimizeButtonHint);
    setWindowTitle(tr("Gaussian filter"));
    setFixedSize(343, 164);
    setModal(true);

    connect(ui->radiusSlider, SIGNAL(valueChanged(int)), ui->radiusSpinBox, SLOT(setValue(int)));
    connect(ui->radiusSpinBox, SIGNAL(valueChanged(int)), ui->radiusSlider, SLOT(setValue(int)));
    connect(ui->sigmaSlider, SIGNAL(valueChanged(int)), this, SLOT(setSpinBoxValue(int)));
    connect(ui->sigmaSpinBox, SIGNAL(valueChanged(double)), this, SLOT(setSliderValue(double)));
    connect(ui->radiusSlider, SIGNAL(valueChanged(int)), this, SLOT(emitRadiusChanged(int)));
    connect(ui->applyButton, SIGNAL(clicked()), this, SLOT(applyButtonClicked()));
    connect(ui->cancelButton, SIGNAL(clicked()), this, SLOT(cancelButtonClicked()));
}

GaussianDialog::~GaussianDialog()
{
    delete ui;
}

void GaussianDialog::setSpinBoxValue(int value)
{
    double temp = (double)value / 100.0;
    ui->sigmaSpinBox->setValue(temp);
}

void GaussianDialog::setSliderValue(double value)
{
    double temp = value * 100;
    ui->sigmaSlider->setValue((int)temp);
    emit sigmaChanged(value);
}

void GaussianDialog::emitRadiusChanged(int value)
{
    emit radiusChanged(value);
    double max = (double)(value * 2 + 1) / 6.0;
    ui->sigmaSpinBox->setMaximum(max);
    max = max * 100;
    ui->sigmaSlider->setMaximum((int)max);
}

void GaussianDialog::setRadius(int radius)
{
    ui->radiusSlider->setValue(radius);
}

void GaussianDialog::setSigma(double sigma)
{
    ui->sigmaSpinBox->setValue(sigma);
}

void GaussianDialog::closeEvent(QCloseEvent *event)
{
    emit cancelFilter();
}

void GaussianDialog::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.setPen(Qt::gray);
    painter.drawRect(10, 10, width() - 20, height() - 20);
}

void GaussianDialog::showEvent(QShowEvent *)
{
    ui->radiusSpinBox->setValue(1);
    ui->sigmaSpinBox->setValue(0.33);
}

void GaussianDialog::applyButtonClicked()
{
    QString str = tr("Gaussian Filter. ")
            + tr("Radius : ") + QString::number(ui->radiusSlider->value())
            + tr(", Sigma : ") + QString::number(ui->sigmaSlider->value()) + tr(".");
    emit applyFilter(str);
    close();
}

void GaussianDialog::cancelButtonClicked()
{
    close();
}
